10 class ApiMainTest
extends ApiTestCase
{
13 * Test that the API will accept a FauxRequest and execute.
15 public function testApi() {
17 new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] )
20 $data = $api->getResult()->getResultData();
21 $this->assertInternalType( 'array', $data );
22 $this->assertArrayHasKey( 'query', $data );
25 public static function provideAssert() {
27 [ false, [], 'user', 'assertuserfailed' ],
28 [ true, [], 'user', false ],
29 [ true, [], 'bot', 'assertbotfailed' ],
30 [ true, [ 'bot' ], 'user', false ],
31 [ true, [ 'bot' ], 'bot', false ],
36 * Tests the assert={user|bot} functionality
38 * @covers ApiMain::checkAsserts
39 * @dataProvider provideAssert
40 * @param bool $registered
41 * @param array $rights
42 * @param string $assert
43 * @param string|bool $error False if no error expected
45 public function testAssert( $registered, $rights, $assert, $error ) {
50 $user->mRights
= $rights;
52 $this->doApiRequest( [
55 ], null, null, $user );
56 $this->assertFalse( $error ); // That no error was expected
57 } catch ( ApiUsageException
$e ) {
58 $this->assertTrue( self
::apiExceptionHasCode( $e, $error ) );
63 * Tests the assertuser= functionality
65 * @covers ApiMain::checkAsserts
67 public function testAssertUser() {
68 $user = $this->getTestUser()->getUser();
69 $this->doApiRequest( [
71 'assertuser' => $user->getName(),
72 ], null, null, $user );
75 $this->doApiRequest( [
77 'assertuser' => $user->getName() . 'X',
78 ], null, null, $user );
79 $this->fail( 'Expected exception not thrown' );
80 } catch ( ApiUsageException
$e ) {
81 $this->assertTrue( self
::apiExceptionHasCode( $e, 'assertnameduserfailed' ) );
86 * Test if all classes in the main module manager exists
88 public function testClassNamesInModuleManager() {
90 new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] )
92 $modules = $api->getModuleManager()->getNamesWithClasses();
94 foreach ( $modules as $name => $class ) {
96 class_exists( $class ),
97 'Class ' . $class . ' for api module ' . $name . ' does not exist (with exact case)'
103 * Test HTTP precondition headers
105 * @covers ApiMain::checkConditionalRequestHeaders
106 * @dataProvider provideCheckConditionalRequestHeaders
107 * @param array $headers HTTP headers
108 * @param array $conditions Return data for ApiBase::getConditionalRequestData
109 * @param int $status Expected response status
110 * @param bool $post Request is a POST
112 public function testCheckConditionalRequestHeaders(
113 $headers, $conditions, $status, $post = false
115 $request = new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ], $post );
116 $request->setHeaders( $headers );
117 $request->response()->statusHeader( 200 ); // Why doesn't it default?
119 $context = $this->apiContext
->newTestContext( $request, null );
120 $api = new ApiMain( $context );
121 $priv = TestingAccessWrapper
::newFromObject( $api );
122 $priv->mInternalMode
= false;
124 $module = $this->getMockBuilder( 'ApiBase' )
125 ->setConstructorArgs( [ $api, 'mock' ] )
126 ->setMethods( [ 'getConditionalRequestData' ] )
127 ->getMockForAbstractClass();
128 $module->expects( $this->any() )
129 ->method( 'getConditionalRequestData' )
130 ->will( $this->returnCallback( function ( $condition ) use ( $conditions ) {
131 return isset( $conditions[$condition] ) ?
$conditions[$condition] : null;
134 $ret = $priv->checkConditionalRequestHeaders( $module );
136 $this->assertSame( $status, $request->response()->getStatusCode() );
137 $this->assertSame( $status === 200, $ret );
140 public static function provideCheckConditionalRequestHeaders() {
144 // Non-existing from module is ignored
145 [ [ 'If-None-Match' => '"foo", "bar"' ], [], 200 ],
146 [ [ 'If-Modified-Since' => 'Tue, 18 Aug 2015 00:00:00 GMT' ], [], 200 ],
153 'last-modified' => '20150815000000',
158 // Basic If-None-Match
159 [ [ 'If-None-Match' => '"foo", "bar"' ], [ 'etag' => '"bar"' ], 304 ],
160 [ [ 'If-None-Match' => '"foo", "bar"' ], [ 'etag' => '"baz"' ], 200 ],
161 [ [ 'If-None-Match' => '"foo"' ], [ 'etag' => 'W/"foo"' ], 304 ],
162 [ [ 'If-None-Match' => 'W/"foo"' ], [ 'etag' => '"foo"' ], 304 ],
163 [ [ 'If-None-Match' => 'W/"foo"' ], [ 'etag' => 'W/"foo"' ], 304 ],
165 // Pointless, but supported
166 [ [ 'If-None-Match' => '*' ], [], 304 ],
168 // Basic If-Modified-Since
169 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822
, $now ) ],
170 [ 'last-modified' => wfTimestamp( TS_MW
, $now - 1 ) ], 304 ],
171 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822
, $now ) ],
172 [ 'last-modified' => wfTimestamp( TS_MW
, $now ) ], 304 ],
173 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822
, $now ) ],
174 [ 'last-modified' => wfTimestamp( TS_MW
, $now +
1 ) ], 200 ],
176 // If-Modified-Since ignored when If-None-Match is given too
177 [ [ 'If-None-Match' => '""', 'If-Modified-Since' => wfTimestamp( TS_RFC2822
, $now ) ],
178 [ 'etag' => '"x"', 'last-modified' => wfTimestamp( TS_MW
, $now - 1 ) ], 200 ],
179 [ [ 'If-None-Match' => '""', 'If-Modified-Since' => wfTimestamp( TS_RFC2822
, $now ) ],
180 [ 'last-modified' => wfTimestamp( TS_MW
, $now - 1 ) ], 304 ],
183 [ [ 'If-None-Match' => '"foo", "bar"' ], [ 'etag' => '"bar"' ], 200, true ],
184 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822
, $now ) ],
185 [ 'last-modified' => wfTimestamp( TS_MW
, $now - 1 ) ], 200, true ],
187 // Other date formats allowed by the RFC
188 [ [ 'If-Modified-Since' => gmdate( 'l, d-M-y H:i:s', $now ) . ' GMT' ],
189 [ 'last-modified' => wfTimestamp( TS_MW
, $now - 1 ) ], 304 ],
190 [ [ 'If-Modified-Since' => gmdate( 'D M j H:i:s Y', $now ) ],
191 [ 'last-modified' => wfTimestamp( TS_MW
, $now - 1 ) ], 304 ],
193 // Old browser extension to HTTP/1.0
194 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822
, $now ) . '; length=123' ],
195 [ 'last-modified' => wfTimestamp( TS_MW
, $now - 1 ) ], 304 ],
197 // Invalid date formats should be ignored
198 [ [ 'If-Modified-Since' => gmdate( 'Y-m-d H:i:s', $now ) . ' GMT' ],
199 [ 'last-modified' => wfTimestamp( TS_MW
, $now - 1 ) ], 200 ],
204 * Test conditional headers output
205 * @dataProvider provideConditionalRequestHeadersOutput
206 * @param array $conditions Return data for ApiBase::getConditionalRequestData
207 * @param array $headers Expected output headers
208 * @param bool $isError $isError flag
209 * @param bool $post Request is a POST
211 public function testConditionalRequestHeadersOutput(
212 $conditions, $headers, $isError = false, $post = false
214 $request = new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ], $post );
215 $response = $request->response();
217 $api = new ApiMain( $request );
218 $priv = TestingAccessWrapper
::newFromObject( $api );
219 $priv->mInternalMode
= false;
221 $module = $this->getMockBuilder( 'ApiBase' )
222 ->setConstructorArgs( [ $api, 'mock' ] )
223 ->setMethods( [ 'getConditionalRequestData' ] )
224 ->getMockForAbstractClass();
225 $module->expects( $this->any() )
226 ->method( 'getConditionalRequestData' )
227 ->will( $this->returnCallback( function ( $condition ) use ( $conditions ) {
228 return isset( $conditions[$condition] ) ?
$conditions[$condition] : null;
230 $priv->mModule
= $module;
232 $priv->sendCacheHeaders( $isError );
234 foreach ( [ 'Last-Modified', 'ETag' ] as $header ) {
236 isset( $headers[$header] ) ?
$headers[$header] : null,
237 $response->getHeader( $header ),
243 public static function provideConditionalRequestHeadersOutput() {
250 [ 'etag' => '"foo"' ],
251 [ 'ETag' => '"foo"' ]
254 [ 'last-modified' => '20150818000102' ],
255 [ 'Last-Modified' => 'Tue, 18 Aug 2015 00:01:02 GMT' ]
258 [ 'etag' => '"foo"', 'last-modified' => '20150818000102' ],
259 [ 'ETag' => '"foo"', 'Last-Modified' => 'Tue, 18 Aug 2015 00:01:02 GMT' ]
262 [ 'etag' => '"foo"', 'last-modified' => '20150818000102' ],
267 [ 'etag' => '"foo"', 'last-modified' => '20150818000102' ],
276 * @covers ApiMain::lacksSameOriginSecurity
278 public function testLacksSameOriginSecurity() {
280 $main = new ApiMain( new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] ) );
281 $this->assertFalse( $main->lacksSameOriginSecurity(), 'Basic test, should have security' );
285 new FauxRequest( [ 'action' => 'query', 'format' => 'xml', 'callback' => 'foo' ] )
287 $this->assertTrue( $main->lacksSameOriginSecurity(), 'JSONp, should lack security' );
290 $request = new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] );
291 $request->setHeader( 'TrEaT-As-UnTrUsTeD', '' ); // With falsey value!
292 $main = new ApiMain( $request );
293 $this->assertTrue( $main->lacksSameOriginSecurity(), 'Header supplied, should lack security' );
296 $this->mergeMwGlobalArrayValue( 'wgHooks', [
297 'RequestHasSameOriginSecurity' => [ function () {
301 $main = new ApiMain( new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] ) );
302 $this->assertTrue( $main->lacksSameOriginSecurity(), 'Hook, should lack security' );
306 * Test proper creation of the ApiErrorFormatter
307 * @covers ApiMain::__construct
308 * @dataProvider provideApiErrorFormatterCreation
309 * @param array $request Request parameters
310 * @param array $expect Expected data
311 * - uselang: ApiMain language
312 * - class: ApiErrorFormatter class
313 * - lang: ApiErrorFormatter language
314 * - format: ApiErrorFormatter format
315 * - usedb: ApiErrorFormatter use-database flag
317 public function testApiErrorFormatterCreation( array $request, array $expect ) {
318 $context = new RequestContext();
319 $context->setRequest( new FauxRequest( $request ) );
320 $context->setLanguage( 'ru' );
322 $main = new ApiMain( $context );
323 $formatter = $main->getErrorFormatter();
324 $wrappedFormatter = TestingAccessWrapper
::newFromObject( $formatter );
326 $this->assertSame( $expect['uselang'], $main->getLanguage()->getCode() );
327 $this->assertInstanceOf( $expect['class'], $formatter );
328 $this->assertSame( $expect['lang'], $formatter->getLanguage()->getCode() );
329 $this->assertSame( $expect['format'], $wrappedFormatter->format
);
330 $this->assertSame( $expect['usedb'], $wrappedFormatter->useDB
);
333 public static function provideApiErrorFormatterCreation() {
335 'Default (BC)' => [ [], [
337 'class' => ApiErrorFormatter_BackCompat
::class,
342 'BC ignores fields' => [ [ 'errorlang' => 'de', 'errorsuselocal' => 1 ], [
344 'class' => ApiErrorFormatter_BackCompat
::class,
349 'Explicit BC' => [ [ 'errorformat' => 'bc' ], [
351 'class' => ApiErrorFormatter_BackCompat
::class,
356 'Basic' => [ [ 'errorformat' => 'wikitext' ], [
358 'class' => ApiErrorFormatter
::class,
360 'format' => 'wikitext',
363 'Follows uselang' => [ [ 'uselang' => 'fr', 'errorformat' => 'plaintext' ], [
365 'class' => ApiErrorFormatter
::class,
367 'format' => 'plaintext',
370 'Explicitly follows uselang' => [
371 [ 'uselang' => 'fr', 'errorlang' => 'uselang', 'errorformat' => 'plaintext' ],
374 'class' => ApiErrorFormatter
::class,
376 'format' => 'plaintext',
380 'uselang=content' => [
381 [ 'uselang' => 'content', 'errorformat' => 'plaintext' ],
384 'class' => ApiErrorFormatter
::class,
386 'format' => 'plaintext',
390 'errorlang=content' => [
391 [ 'errorlang' => 'content', 'errorformat' => 'plaintext' ],
394 'class' => ApiErrorFormatter
::class,
396 'format' => 'plaintext',
400 'Explicit parameters' => [
401 [ 'errorlang' => 'de', 'errorformat' => 'html', 'errorsuselocal' => 1 ],
404 'class' => ApiErrorFormatter
::class,
410 'Explicit parameters override uselang' => [
411 [ 'errorlang' => 'de', 'uselang' => 'fr', 'errorformat' => 'raw' ],
414 'class' => ApiErrorFormatter
::class,
420 'Bogus language doesn\'t explode' => [
421 [ 'errorlang' => '<bogus1>', 'uselang' => '<bogus2>', 'errorformat' => 'none' ],
424 'class' => ApiErrorFormatter
::class,
430 'Bogus format doesn\'t explode' => [ [ 'errorformat' => 'bogus' ], [
432 'class' => ApiErrorFormatter_BackCompat
::class,
441 * @covers ApiMain::errorMessagesFromException
442 * @covers ApiMain::substituteResultWithError
443 * @dataProvider provideExceptionErrors
444 * @param Exception $exception
445 * @param array $expectReturn
446 * @param array $expectResult
448 public function testExceptionErrors( $error, $expectReturn, $expectResult ) {
449 $context = new RequestContext();
450 $context->setRequest( new FauxRequest( [ 'errorformat' => 'plaintext' ] ) );
451 $context->setLanguage( 'en' );
452 $context->setConfig( new MultiConfig( [
454 'ShowHostnames' => true, 'ShowSQLErrors' => false,
455 'ShowExceptionDetails' => true, 'ShowDBErrorBacktrace' => true,
457 $context->getConfig()
460 $main = new ApiMain( $context );
461 $main->addWarning( new RawMessage( 'existing warning' ), 'existing-warning' );
462 $main->addError( new RawMessage( 'existing error' ), 'existing-error' );
464 $ret = TestingAccessWrapper
::newFromObject( $main )->substituteResultWithError( $error );
465 $this->assertSame( $expectReturn, $ret );
467 // PHPUnit sometimes adds some SplObjectStorage garbage to the arrays,
468 // so let's try ->assertEquals().
471 $main->getResult()->getResultData( [], [ 'Strip' => 'all' ] )
475 // Not static so $this can be used
476 public function provideExceptionErrors() {
477 $reqId = WebRequest
::getRequestId();
478 $doclink = wfExpandUrl( wfScript( 'api' ) );
480 $ex = new InvalidArgumentException( 'Random exception' );
481 $trace = wfMessage( 'api-exception-trace',
485 MWExceptionHandler
::getRedactedTraceAsString( $ex )
486 )->inLanguage( 'en' )->useDatabase( false )->text();
488 $dbex = new DBQueryError(
489 $this->createMock( 'IDatabase' ),
490 'error', 1234, 'SELECT 1', __METHOD__
);
491 $dbtrace = wfMessage( 'api-exception-trace',
495 MWExceptionHandler
::getRedactedTraceAsString( $dbex )
496 )->inLanguage( 'en' )->useDatabase( false )->text();
498 $apiEx1 = new ApiUsageException( null,
499 StatusValue
::newFatal( new ApiRawMessage( 'An error', 'sv-error1' ) ) );
500 TestingAccessWrapper
::newFromObject( $apiEx1 )->modulePath
= 'foo+bar';
501 $apiEx1->getStatusValue()->warning( new ApiRawMessage( 'A warning', 'sv-warn1' ) );
502 $apiEx1->getStatusValue()->warning( new ApiRawMessage( 'Another warning', 'sv-warn2' ) );
503 $apiEx1->getStatusValue()->fatal( new ApiRawMessage( 'Another error', 'sv-error2' ) );
508 [ 'existing-error', 'internal_api_error_InvalidArgumentException' ],
511 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
514 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
516 'code' => 'internal_api_error_InvalidArgumentException',
517 'text' => "[$reqId] Exception caught: Random exception",
521 'servedby' => wfHostname(),
526 [ 'existing-error', 'internal_api_error_DBQueryError' ],
529 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
532 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
534 'code' => 'internal_api_error_DBQueryError',
535 'text' => "[$reqId] Database query error.",
539 'servedby' => wfHostname(),
543 new UsageException( 'Usage exception!', 'ue', 0, [ 'foo' => 'bar' ] ),
544 [ 'existing-error', 'ue' ],
547 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
550 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
551 [ 'code' => 'ue', 'text' => "Usage exception!", 'data' => [ 'foo' => 'bar' ] ]
553 'docref' => "See $doclink for API usage. Subscribe to the mediawiki-api-announce mailing " .
554 "list at <https://lists.wikimedia.org/mailman/listinfo/mediawiki-api-announce> " .
555 "for notice of API deprecations and breaking changes.",
556 'servedby' => wfHostname(),
561 [ 'existing-error', 'sv-error1', 'sv-error2' ],
564 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
565 [ 'code' => 'sv-warn1', 'text' => 'A warning', 'module' => 'foo+bar' ],
566 [ 'code' => 'sv-warn2', 'text' => 'Another warning', 'module' => 'foo+bar' ],
569 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
570 [ 'code' => 'sv-error1', 'text' => 'An error', 'module' => 'foo+bar' ],
571 [ 'code' => 'sv-error2', 'text' => 'Another error', 'module' => 'foo+bar' ],
573 'docref' => "See $doclink for API usage. Subscribe to the mediawiki-api-announce mailing " .
574 "list at <https://lists.wikimedia.org/mailman/listinfo/mediawiki-api-announce> " .
575 "for notice of API deprecations and breaking changes.",
576 'servedby' => wfHostname(),